package com.ruoyi.task;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import com.common.util.ListConvertMap;
import com.common.util.MergeDataSource;
import com.ruoyi.configuration.domain.MgTeamSigningRewards;
import com.ruoyi.pay.manager.domain.PayManager;
import com.ruoyi.pay.manager.service.IPayManagerService;
import com.ruoyi.team.domain.vo.MgTeam;
import com.ruoyi.team.service.ITeamInformationService;

public class ParsePrice implements Runnable {

	static Logger logger = LoggerFactory.getLogger(ParsePrice.class);
	
	public static Long nextId;
	

	static ReentrantLock lock = new ReentrantLock();

	private List<MgTeamSigningRewards> teamSigningRewards;

	private ITeamInformationService teamInformationService;

	private IPayManagerService payManagerService;

	private RedisTemplate<String, Object> redisTemplate;

	private long start;

	private long num;

	private long startByPaymanagerId;

	public List<MgTeamSigningRewards> getTeamSigningRewards() {
		return teamSigningRewards;
	}

	public void setTeamSigningRewards(List<MgTeamSigningRewards> teamSigningRewards) {
		this.teamSigningRewards = teamSigningRewards;
	}

	public ParsePrice(ITeamInformationService teamInformationService, IPayManagerService payManagerService,
			RedisTemplate<String, Object> redisTemplate, List<MgTeamSigningRewards> teamSigningRewards) {

		this.teamInformationService = teamInformationService;

		teamSigningRewards.sort((f, s) -> s.getPrice().compareTo(f.getPrice()));

		this.teamSigningRewards = teamSigningRewards;

		this.payManagerService = payManagerService;

		this.redisTemplate = redisTemplate;

	}

	public long getStart() {
		return start;
	}

	public void setStart(long start) {
		this.start = start;
	}

	@Override
	public void run() {

		List<MgTeam> selectTeamList;
		
		try {
			

//			Object object = opsForHash.get("team-min-id", "id" + start);

			lock.lock();
			
			long realStart = start;

			if (null != nextId) {

				realStart = nextId - 1;
			}


			selectTeamList = teamInformationService.selectTeamList(realStart, num);

			int size = selectTeamList.size();
			
//			logger.error("start: {}, realStart: {}, nextId:{}, size: {}, lock: {}", start, realStart, nextId, size, lock);
			
			if (0 == size) {
				return;
			}

			MgTeam mgTeam = selectTeamList.get(size - 1);
			nextId = mgTeam.getId().longValue();

		} finally {
			lock.unlock();
		}

		List<PayManager> selectListByBetweenTeamId = payManagerService
				.selectListByBetweenTeamId(selectTeamList.stream().mapToLong(e -> e.getId()).toArray());

		Map<Integer, PayManager> listToMap = ListConvertMap.listToMap(selectListByBetweenTeamId, PayManager::getTeamId);

		MergeDataSource<MgTeam> mergeDataSource = new MergeDataSource<MgTeam>(selectTeamList);

		mergeDataSource.mergeRelease(MgTeam::getId, listToMap, (team, item) -> {

			team.setTotalMoney(item.getPriceSum());
			return team;
		});

		BigDecimal totalMoney;

		List<MgTeam> mgTeams = new ArrayList<MgTeam>();
		
//		logger.debug("selectTeamList: {}", selectTeamList);
		
		int size = teamSigningRewards.size();
		
		BigDecimal onhandruid = new BigDecimal(100);
		
		
		if (0 == size) {
			
			// 团队折扣重置100
			
			
			for (MgTeam team : selectTeamList ) {
				team.setDiscount(onhandruid);
			}
			
			teamInformationService.updateDiscount(selectTeamList);
		}
		

		for (MgTeam team : selectTeamList ) {

//			Byte type = rewards.getType();

			totalMoney = team.getTotalMoney();

			for (MgTeamSigningRewards rewards : teamSigningRewards) {
				//
				if (0 < totalMoney.compareTo(rewards.getPrice())) {

					team.setDiscount(rewards.getDiscount());
					
//					logger.debug("team:{}, price: {}, total_price: {}, 名称：{}", 
//							rewards.getDiscount(), rewards.getPrice(), totalMoney, team.getGroupName());
					
					mgTeams.add(team);
					break;
				}
			}
		}

		if (0 == mgTeams.size()) {
			return;
		}
		
		Map<Integer, MgTeam> alreadyData = ListConvertMap.listToMap(mgTeams, MgTeam::getId);
		
		for (MgTeam team : selectTeamList ) {
			
			MgTeam mgTeam = alreadyData.get(team.getId());
			
			if (null == mgTeam) {
				team.setDiscount(onhandruid);
                continue;
            }
			team.setDiscount(mgTeam.getDiscount());
			
		}
		
		teamInformationService.updateDiscount(selectTeamList);
	}

	public long getNum() {
		return num;
	}

	public void setNum(long num) {
		this.num = num;
	}

	public long getStartByPaymanagerId() {
		return startByPaymanagerId;
	}

	public void setStartByPaymanagerId(long startByPaymanagerId) {
		this.startByPaymanagerId = startByPaymanagerId;
	}

}
